<template>
  <div class="form-container">
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>文章管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/articleList' }">文章列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加文章</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="form-content">

      <el-form ref="form" :model="form" :rules="rules" label-width="126px">
        <el-form-item label="文章分类" prop="type_id">
          <el-cascader
            ref="organizerUnit"
            @change="handleParentType"
            :options="types"
            v-model="form.type_id"
            :show-all-levels="false"
            clearable
            :props="{checkStrictly:true,emitPath:false}"
            placeholder="请选择商品分类"></el-cascader>
        </el-form-item>

        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>

        <el-form-item label="文章作者">
          <el-input v-model="form.author" placeholder="请输入文章作者"></el-input>
        </el-form-item>

        <el-form-item label="简介">
          <el-col>
            <el-input type="textarea" v-model="form.brief"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
            action="/api/client/base/uploadfile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            ref="upload"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="true"
            :limit="50"
            :headers="myHeaders"
            :file-list="fileList"
            accept="image/jpeg, image/jpg, image/gif, image/png"
            :multiple="false">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>

        </el-form-item>
        <el-form-item label="文章标签" >
          <el-input v-model="form.tag" placeholder="多个请使用英文逗号隔开"></el-input>
        </el-form-item>
        <el-form-item label="文章内容">
          <VueEditor style="width: 100%"
                     v-loading="editorLoading"
                     element-loading-text="图片上传中"
                     element-loading-background="rgba(0, 0, 0, 0.5)"
                     useCustomImageHandler
                     @image-added="handleImageAdded"
                     :editorToolbar="customToolbar"
                     v-model="form.content"/>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="form.category_id">
            <el-radio :label="0">普通文章</el-radio>
            <el-radio :label="1">音频文章</el-radio>
            <el-radio :label="2">视频文章</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传音频" v-if="form.category_id==1">
          <el-upload
              ref="replaceUploader"
              :file-list="replaceList"
              class="avatar-uploader"
              action="/api/client/base/uploadfile"
              :limit="1"
              :show-file-list="true"
              :on-success="handleReplaceAvatarSuccess"
              :on-exceed="handleExceed"
              :on-remove="removeReplace"
              :beforeUpload="beforeReplaceAvatarUpload">
              <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="上传视频" v-if="form.category_id==2">
          <div class="item">
            <el-upload
                class="avatar-uploader el-upload--text avatar"
                action="/api/client/base/uploadfile"
                :show-file-list="false"
                :on-success="handleVideoSuccess"
                :before-upload="beforeUploadVideo"
                :on-progress="uploadVideoProcess">
                <video
                v-if="videoUrl != '' && videoFlag == false"
                :src="videoUrl"
                controls="controls"
                >
                您的浏览器不支持视频播放
                </video>
                <i v-if="videoUrl == '' && videoFlag == false"
                class="el-icon-plus avatar-uploader-icon"
                ></i>
                <el-progress
                v-if="videoFlag == true"
                type="circle"
                :percentage="videoUploadPercent"
                style="margin-top:30px;"
                ></el-progress>
                <div class="uploadLabel" v-if="videoUrl!==''" @click.stop="closeVideo">
                    <i class="el-icon-close"></i>
                </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="是否发布">
          <el-switch v-model="form.is_pub"></el-switch>
        </el-form-item>
        <el-form-item label="排序">
          <el-col :span="5">
            <el-input v-model="form.sort" placeholder="数字越大越靠后"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-row>
            <el-button type="danger" @click="confirmAdd('form')">立即保存</el-button>
            <el-button type="default" @click="cancel()">返回</el-button>
          </el-row>
        </el-form-item>

      </el-form>
    </div>
    
  </div>

</template>

<script>
  import {VueEditor} from 'vue2-editor'

  export default {
    components: {VueEditor},
    name: 'Vue2Editor',
    data() {
      return {
        validate: false,
        activeName: 'first',
        types: [],
        form: {
          tag:'',
          author:'',
          cover: '',
          type_id: '',
          title: '',
          is_pub: true,
          sort: 0,
          brief: '',
          group_id: '2',
          content: '',
          category_id:0,
          category_txt:''
        },
        videoUrl:'',//视频连接
        videoId:'',//视频id
        videoFlag:false,
        videoUploadPercent:0,

        replaceList:[],

        rules: {
          type_id: [
            {required: true, message: '请选择文章分类', trigger: 'blur'}
          ],
          title: [
            {required: true, message: '请输入文章标题', trigger: 'blur'},
          ],

        },
        filter_keyword: '',
        editorLoading: false, //富文本图片loading
        customToolbar: [
          [{header: [false, 1, 2, 3, 4, 5, 6]}], //标题
          ['bold', 'italic', 'underline','strike'], //加粗\斜体\下划线\作废
          ['blockquote', 'code-block'],
          [{
            'script': 'sub'
          }, {
            'script': 'super'
          }], // superscript/subscript
          [{
            'indent': '-1'
          }, {
            'indent': '+1'
          }], // outdent/indent
          [{
            'direction': 'rtl'
          }],
          [{align: ''}, {align: 'center'}, {align: 'right'}], //对齐
          [{list: 'ordered'}, {list: 'bullet'}, {list: 'check'}], //有序无序列表
          [{background: []}, {color: []}], //背景色
          ['image', 'link'], //图片、链接
          ['clean'], //清楚格式（所谓去掉背景色这些花里胡巧）
          ['code'], //代码
          ['code-block'], //代码块
          //['video'] //视频
        ],
        fileList: [],
        dialogImageUrl: "",
        dialogVisible: false,
        myHeaders: {
          'access-token': this.$store.state.token, //这里重新定义了请求头
          'Authorization': this.$store.state.token,
          'user-id': this.$store.state.user_id
        },
      }
    },
    mounted() {
      this.loadTypes();
    },
    methods: {
      handleRemove(file, fileList) {
        this.fileList = fileList
      },
      handlePictureCardPreview(file) {
        console.log('file', file);
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleAvatarSuccess(res, file, fileList) {
        console.log('fileList', fileList);
        this.fileList = fileList
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传商品图片大小不能超过 2MB!');
        }
        return isLt2M;
      },

      // 验证视频格式
      beforeUploadVideo(file) {
          if (
              [
              'video/mp4',
              'video/ogg',
              'video/flv',
              'video/avi',
              'video/wmv',
              'video/rmvb'
              ].indexOf(file.type) === -1
          ) {
              this.$message.error('请上传正确的视频格式')
              return false
          }
          const isLt2M = file.size / 1024 / 1024 < 30;
          if (!isLt2M) {
              this.$message.error('上传视频大小不能超过 30MB!');
          }
      },
      // 上传进度显示
      uploadVideoProcess(event, file, fileList) {
          console.log(event.percent, file, fileList)
          this.videoFlag = true
          this.videoUploadPercent = Math.floor(event.percent)
      },

      // 获取上传地址
      handleVideoSuccess(res, file) {
          this.videoFlag = false
          this.videoUploadPercent = 0
          console.log(res,file,'视频上传')
          this.videoUrl = file.response.data.url
          this.videoId = file.response.data.id
      },

      // 删除视频按钮
      closeVideo(){
          this.videoUrl = ''
          this.videoId = ''
      },

      // 上传音频
      handleReplaceAvatarSuccess(res,file,fileList){
        console.log(file,fileList,'音频');
        this.replaceList = fileList
      },
      beforeReplaceAvatarUpload(file){
         var testmsg = file.name.substring(file.name.lastIndexOf('.')+1)
         const extension = testmsg === 'mp3'
         if(!extension){
           this.$message({
             message:"上传文件只能是mp3格式！",
             type:'error'
           })
         }
         return extension;
      },
      handleExceed(){
        // console.log('超出个数');
        this.$message.warning('最多上传一个')
      },
      // 删除音频
      removeReplace(file,fileList){
        console.log(file,fileList,'1111');
        this.replaceList = fileList
      },

      confirmAdd(form) {
        this.validateFormData(form);
        if (this.validate) {
          const _ths = this;
          // if(this.form.type_id.length > 0){
          //   this.form.type_id = this.form.type_id.pop();
          // }
          if (this.fileList.length > 0) {
            this.fileList.map(v => {
              if (v.response) {
                _ths.form.cover = v.response.data.id;
              } else {
                _ths.form.cover = v.id;
              }
            })
          }
          if(this.form.category_id==1){
            if(!this.replaceList.length){
              this.$message.warning('请上传音频')
              return
            }
            this.replaceList.map(v => {
              if (v.response) {
                _ths.form.category_txt = v.response.data.id;
              } else {
                _ths.form.category_txt = v.id;
              }
            })
          }
          if(this.form.category_id==2){
            if(this.videoId==''){
              this.$message.warning('请上传视频')
              return
            }
            this.form.category_txt = this.videoId;
          }
          this.$http.post('/api/root/article/add', {...this.form})
            .then(rest => {
              if (rest.msg == 'ok') {
                this.$message.success('添加成功');
                setTimeout(function () {
                  _ths.$router.push({name: 'articleList'})
                }, 800)
              } else {
                this.form = {
                  ...this.form,
                };
                this.$message.error(rest.msg);
              }
            })
        }
      },
      cancel() {
        this.$router.push({name: 'articleList'})
      },

      /**
       * 验证表单数据
       * @param form
       */
      validateFormData(form) {
        this.$refs[form].validate((valid) => {
          if (!valid) {
            this.$message({
              message: '表单数据未填写完整,操作失败！',
              type: 'warning'
            });
            return false;
          }
          this.validate = true;
          return true;
        })
      },
      //富文本上传图片
      handleImageAdded(file, Editor, cursorLocation, resetUploader) {
        var formData = new FormData()
        let isLtSize = file.size / 1024 / 1024 < 10
        if (!isLtSize) {
          this.$message.warning('上传文件不能超过 10MB!')
          return
        }
        this.editorLoading = true;
        formData.append('file', file);
        this.$http.post('/api/admin/base/uploadfile', formData)
          .then((result) => {
            if (result.msg !== 'ok' || !result.data){
              this.$message.error(result.msg);
              this.editorLoading = false;
              resetUploader();
              return false;
            }
            // 你上传路径返回的url
            let url = result.data.url;
            if (file.type === 'video/mp4') {
              Editor.insertEmbed(cursorLocation, 'video', url);//视频
            } else if (file.type === 'audio/mpeg') {
              Editor.insertEmbed(cursorLocation, 'video', url);//音频
            } else {
              Editor.insertEmbed(cursorLocation, 'image', url)
            }
            resetUploader();
            this.editorLoading = false
          }).catch((err) => {
            this.editorLoading = false
          })
      },
      loadTypes() {
        var _ths = this;
        this.$http.post('/api/root/article/articleTypes', {})
          .then((rest) => {
            if (rest.data.length > 0) {
              _ths.types = rest.data;
            }
          })
      },
      handleParentType(value) {
        this.form.pid = value;
        if (this.$refs.organizerUnit) {
          this.$refs.organizerUnit.dropDownVisible = false
        }
      },

    }
  }
</script>
<style lang="less" scoped>
  @import "index.less";
</style>